#include "logfile.h"
#include <time.h>
#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)

CLogFile::CLogFile(const char* pchFile)
{
	m_pFile = NULL;
	m_dwWriteTimer = 0;
	memset(m_szFile,0,MAX_BUFFLEN);
	memset(m_szTimer,0,MAX_BUFFLEN);
	memset(m_szBuffer,0,MAX_BUFFLEN);

	CreateDirectory("syslog", NULL);

	Init(pchFile);
}

CLogFile::~CLogFile()
{
	if(m_pFile)
	{
		fclose(m_pFile);
		m_pFile = NULL;
	}
	m_dwWriteTimer = 0;
	memset(m_szFile,0,MAX_BUFFLEN);
	memset(m_szTimer,0,MAX_BUFFLEN);
	memset(m_szBuffer,0,MAX_BUFFLEN);
}

BOOL CLogFile::Init(const char* pchFile)
{
	m_dwWriteTimer = 0;
	strcpy_s(m_szFile,MAX_BUFFLEN,pchFile);
	m_pFile = fopen(GetLogFile(m_szFile),"wb");
	if(!m_pFile)
	{
		return FALSE;
	}
	return TRUE;
}

BOOL CLogFile::CreateFile()
{
	if(!m_pFile) return false;

	m_dwWriteTimer = 0;
	long lLen = ftell(m_pFile);
	if(lLen >= (20 * 1024 * 1024))
	{
		if(m_pFile)
		{
			fclose(m_pFile);
			m_pFile = NULL;
		}
		m_pFile = fopen(GetLogFile(m_szFile),"wb");
		if(!m_pFile)
		{
			return FALSE;
		}
	}
	return TRUE;
}

BOOL CLogFile::Log(char* pchMsg, ...)
{
	if(!m_pFile)
	{
		return FALSE;
	}
	CSyncEvent sys(&m_cs);
	va_list listArgs;
	va_start(listArgs,pchMsg);
	_vsnprintf_s(m_szBuffer,MAX_BUFFLEN,MAX_BUFFLEN,pchMsg,listArgs);
	va_end(listArgs);
	fprintf(m_pFile,"%s %s\r\n",GetTimer(),m_szBuffer);
	fflush(m_pFile);
	CreateFile();
	return TRUE;
};

char* CLogFile::GetLogFile(char* pchFile)
{
	time_t timeLong;
	time(&timeLong);
	struct tm tTimer;
	localtime_s(&tTimer,&timeLong);
	sprintf_s(m_szTimer,64,"sysLog/%s_%d%d%d_%d%d%d.log",pchFile,tTimer.tm_year + 1900,tTimer.tm_mon + 1,tTimer.tm_mday,tTimer.tm_hour,tTimer.tm_min,tTimer.tm_sec);
	return m_szTimer;
}

char* CLogFile::GetTimer()
{
	time_t timeLong;
	time(&timeLong);
	struct tm tTimer;
	localtime_s(&tTimer,&timeLong);
	sprintf_s(m_szTimer,64,"%d-%d-%d_%d:%d:%d",tTimer.tm_year + 1900,tTimer.tm_mon + 1,tTimer.tm_mday,tTimer.tm_hour,tTimer.tm_min,tTimer.tm_sec);
	return m_szTimer;
};

